package io.github.novaframe.web.error;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.github.novaframe.config.NovaframeCode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 错误消息View Model
 * Created by Locki on 8/9/2017.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class ErrorVM implements Serializable {

    private static final long serialVersionUID = -1585321124085223652L;

    @JsonProperty("errcode")
    private Integer errCode;
    @JsonProperty("errmsg")
    private String errMsg;
    @JsonProperty("fieldErrors")
    private List<FieldErrorVM> fieldErrors;

    public static ErrorVM success() {
        return new ErrorVM(NovaframeCode.SUCCESS);
    }

    public static ErrorVM error() {
        return new ErrorVM(NovaframeCode.SYSTEM_BUSY);
    }

    public ErrorVM() {}

    public ErrorVM(ErrorCode errorCode) {
        this(errorCode.value(), errorCode.desc());
    }

    public ErrorVM(Integer errCode) {
        this(errCode, null);
    }

    public ErrorVM(Integer errCode, String errMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
    }

    public ErrorVM(Integer errCode, String errMsg, List<FieldErrorVM> fieldErrors) {
        this.errCode = errCode;
        this.errMsg = errMsg;
        this.fieldErrors = fieldErrors;
    }

    public void add(String objectName, String field, String message) {
        if (fieldErrors == null) {
            fieldErrors = new ArrayList<>();
        }
        fieldErrors.add(new FieldErrorVM(objectName, field, message));
    }

    public Integer getErrCode() {
        return errCode;
    }

    public String getErrMsg() {
        return errMsg;
    }

    @JsonIgnore
    public Boolean isSuccess() {
        return this.errCode == 0;
    }

    public List<FieldErrorVM> getFieldErrors() {
        return fieldErrors;
    }
}
